package org.lex.swing;

import java.util.IdentityHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import javax.swing.JTree;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

public class TreeUtils {
	public static void expand(JTree tree) {
        TreeModel model = tree.getModel();
        Queue<Object> currentLevelNodes = new LinkedList<Object>();
        Map<Object, TreePath> paths = new IdentityHashMap<Object, TreePath>();
        Object root = model.getRoot();
        paths.put(root, new TreePath(root));
        currentLevelNodes.offer(root);

        while (false == currentLevelNodes.isEmpty()) {
            Object parent = currentLevelNodes.poll();
            TreePath parentPath = paths.get(parent);
            int childCount = model.getChildCount(parent);
            for (int i = 0; i < childCount; i++) {
                Object child = model.getChild(parent, i);
                TreePath childPath = parentPath.pathByAddingChild(child);
                paths.put(child, childPath);
                currentLevelNodes.offer(child);
            }
        }
        for (TreePath path : paths.values()) {
            tree.expandPath(path);
        }
    }
}
